package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.key.RedisKey;
import cn.wolfcode.luowowo.cache.service.IAnswerCacheService;
import cn.wolfcode.luowowo.cache.service.IQuestionCacheService;
import cn.wolfcode.luowowo.cache.vo.AnswerStats;
import cn.wolfcode.luowowo.cache.vo.QuestionStats;
import cn.wolfcode.luowowo.cache.vo.UserAnswer;
import cn.wolfcode.luowowo.comment.domain.AnswerComment;
import cn.wolfcode.luowowo.comment.domain.QuestionComment;
import cn.wolfcode.luowowo.comment.service.IAnswerCommentService;
import cn.wolfcode.luowowo.comment.service.IQuestionCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/wenda")
public class WendaController {
    @Reference
    private IQuestionCommentService questionCommentService;
    @Reference
    private IAnswerCommentService answerCommentService;
    @Reference
    private IQuestionCacheService questionCacheService;
    @Reference
    private IAnswerCacheService answerCacheService;


    //查询所有的回答
    @RequestMapping("/wenda")
    public String list(Model model) {
        List<QuestionComment> questionList = questionCommentService.list();
        for (QuestionComment questionComment : questionList) {
            //通过提问查出所有的回答
            List<AnswerComment> answerList = answerCommentService.findById(questionComment.getId());
            QuestionStats vo = questionCacheService.getQuestionStats(questionComment.getId());
            if (vo != null) {
                //提问的阅读数
                questionComment.setViewnum(vo.getViewnum());
            }
            //设置回复数就是回答的个数
            questionComment.setReplynum(answerList.size());
            if (answerList.size()>0) {
                answerList = answerList.subList(0, 1);
                //通过回答的id来找到redis中回答的热数据
                AnswerComment answerComment = answerList.get(0);
                AnswerStats answerVo = answerCacheService.getAnswerStats(answerComment.getId());
                answerComment.setThumbupnum(answerVo.getThumbsupnum());
                questionComment.setRefAnawer(answerList);
            }
        }
        model.addAttribute("questions", questionList);
        return "wenda/wenda";
    }


    /**
     *
     * @param type 今日 本周 本月
     * @param rank  金牌 回答 被顶
     * @return
     */
   @RequestMapping("/sort")
    public String  sort(Integer type ,Integer rank,Model model,String key){
       List<UserAnswer> list = answerCacheService.getUserAnswer(type,rank,key);
       model.addAttribute("users", list);
       return  "wenda/wendaTpl";
    }


    //进入我要提问
    @RequireLogin
    @RequestMapping("/public")
    public String addAnswer() {
        return "wenda/public";
    }

    //保存提问
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequireLogin
    public AjaxResult saveOrUpdate(QuestionComment question, @LoginUser UserInfo user) {
        AjaxResult result=new AjaxResult();
        if (question.getTitle()==null || "".equals(question.getTitle())) {
            return result.mark("提问标题不能为空");
        }
       question.setUserId(user.getId());
        question.setUsername(user.getNickname());
        question.setHeadUrl(user.getHeadImgUrl());
        question.setCreateTime(new Date());
        result = questionCommentService.saveOrUpdate(question);
        //把保存的提问 中的热数据放到redis中
        QuestionComment questionComment = (QuestionComment)result.getData();
       if(!questionCacheService.exit(questionComment.getId())){
            QuestionStats vo=new QuestionStats();
           vo.setQId( questionComment.getId());
           vo.setFavornum(questionComment.getSharenum());
           vo.setThumbsupnum(questionComment.getThumbsupnum());
           vo.setViewnum(questionComment.getViewnum());
           vo.setReplynum(questionComment.getReplynum());
          questionCacheService.setQuestionStats(vo);
       }
        return result;
    }

    //保存回答
    @RequestMapping("/saveAnswer")
    @ResponseBody
    @RequireLogin
    public Object saveAnswer(AnswerComment answer, @LoginUser UserInfo user, HttpServletResponse response) throws IOException {
        AjaxResult result=new AjaxResult();
        if (answer.getContent() == null || "".equals(answer.getContent())){
             return result.mark("内容不能为空");
        }
        answer.setUserId(user.getId());
        answer.setUsername(user.getNickname());
        answer.setHeadUrl(user.getHeadImgUrl());
        answer.setLevel(user.getLevel());
        answer.setAnswerTime(new Date());
         result = answerCommentService.saveOrUpdate(answer);
         //每保存一个回答,九百回放到redis中
        AnswerComment answerComment = (AnswerComment)result.getData();
       if(!answerCacheService.exist(answerComment.getId())){
           AnswerStats vo=new AnswerStats();
            vo.setAId(answerComment.getId());
            vo.setThumbsupnum(answerComment.getThumbupnum());
            vo.setQId(answerComment.getQId());
            vo.setUserId(user.getId());
            vo.setHeadUrl(user.getHeadImgUrl());
            vo.setLevel(user.getLevel());
            vo.setUsername(user.getNickname());
            answerCacheService.setAnswerStats(vo);
       }
        if (result.isSuccess()) {
            //每次保存回答就加1
            answerCacheService.setUserAnswerDay(RedisKey.ANSWER_UP_SORT_DAY.getPrefix(),user.getId(),1,0);
            answerCacheService.setUserAnswerDay(RedisKey.ANSWER_UP_SORT_WEEK.getPrefix(),user.getId(),1,1);
            answerCacheService.setUserAnswerDay(RedisKey.ANSWER_UP_SORT_MONTH.getPrefix(),user.getId(),1,2);
        }
        return result;
    }


    //传的是提问id获取问答详细
    @RequestMapping("/wendaDetail")
    public String getWendaDetail(Model model,String id,@LoginUser UserInfo user) {
        if (id != null) {
            questionCacheService.incrNum(id,1,IQuestionCacheService.QUESTION_VIUMNUM);
            //获取提问在redis中的热数据共享过去
            model.addAttribute("vo",questionCacheService.getQuestionStats(id));
        }
       //提问
        model.addAttribute("question",questionCommentService.findById(id));
        //回答
        List<AnswerComment> list = answerCommentService.findById(id);
        model.addAttribute("answers", list);
        //提问的回答个数就是回复数
        model.addAttribute("questionNum",list.size()>0 ? list.size() : 0);

        return "wenda/wendaDetail";
    }


    @Value("${file.dir}")
    private String filePath;

    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }


    //点关注
    @ResponseBody
    @RequestMapping("/attention")
     public Object guanzhu(String qId,@LoginUser UserInfo user) {
        AjaxResult result = new AjaxResult();
        //判断是否有登录,只有登录了才能点收藏
        if (user == null) {
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }
        boolean flag = questionCacheService.getAttention(qId, user.getId());
        result.setSuccess(flag);
        QuestionStats vo = questionCacheService.getQuestionStats(qId);
        result.addData(vo);
        return result;
    }

     //顶一个
    @ResponseBody
    @RequestMapping("/wendaThumbup")
    public Object ding(@LoginUser UserInfo user, String aId,Long userId){
        AjaxResult result = new AjaxResult();
        //判断是否有登录,只有登录了才能点收藏
        if (user == null) {
            result.mark("请先登录");
            result.setCode(102);
            return result;
        }else if (user!=null && user.getId()==userId){
            result.mark("不能给自己顶");
            result.setCode(100);
            return result;
        }
        boolean flag = answerCacheService.answerThumbup(user.getId(), aId);
          result.setSuccess(flag);
        if (flag) {
            //被人顶后,被顶数加1就增加1
            answerCacheService.setuserThumbupDay(RedisKey.THUMBUP_UP_SORT_DAY.getPrefix(),user.getId(),1,0);
            answerCacheService.setuserThumbupDay(RedisKey.THUMBUP_UP_SORT_WEEK.getPrefix(),user.getId(),1,1);
            answerCacheService.setuserThumbupDay(RedisKey.THUMBUP_UP_SORT_MONTH.getPrefix(),user.getId(),1,2);

            //被人顶后,金牌数加1
            answerCacheService.setuserGoldDay(RedisKey.GOLD_UP_SORT_DAY.getPrefix(),user.getId(),1,0);
            answerCacheService.setuserGoldDay(RedisKey.GOLD_UP_SORT_DAY.getPrefix(),user.getId(),1,1);
            answerCacheService.setuserGoldDay(RedisKey.GOLD_UP_SORT_DAY.getPrefix(),user.getId(),1,2);
        }
        AnswerStats vo = answerCacheService.getAnswerStats(aId);
        result.addData(vo);
        return result;
    }


}
